package com.yyj.web.controller;/**
 * Created by Administrator on 2018/5/23.
 */

import com.yyj.common.BaseResponse;
import com.yyj.common.ConfigReader;
import com.yyj.constant.ReturnCode;
import com.yyj.util.DateUtil;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;


/**
 * @author
 * @create 2018-05-23 16:28
 **/
@Api(value = "上传图片接口" , description="上传图片接口")
@RestController
public class UploadFileController extends BaseController{

    @Autowired
    ConfigReader configReader;
    /**
     * 方法描述:文件上传
     *
     * @author leon 2017年7月25日 上午10:54:37
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/uploadFile/{type}", consumes = "multipart/*" , headers = "content-type=multipart/form-data" , method = RequestMethod.POST)
    @ResponseBody
    public BaseResponse uploadMultiFile(@PathVariable String type ,
                                        HttpServletRequest request, HttpServletResponse response) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setRc(ReturnCode.NORMAL_SUCCESS);

        try {
            //上传文件处理器
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            //文件对象
            MultipartFile file = (MultipartFile) multipartRequest.getFile("uploadFile");
            String originalFilename = file.getOriginalFilename();
            String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            //String savedDir = request.getSession().getServletContext().getRealPath("uploadFile"); //获取服务器指定文件存取路径
            String savedDir = configReader.getUploadFilePath();
            String filePath = type + File.separator + DateUtil.getNowShortDate() + File.separator;
            savedDir = savedDir + File.separator + filePath;
            logger.info("savedDir:" + savedDir);
            String fileName = System.currentTimeMillis() + substring;
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(savedDir,fileName));
            baseResponse.setData(configReader.getImagePath() + "/upload/images/yyj/" + type + "/" + DateUtil.getNowShortDate() + "/" + fileName);

        } catch (Exception e) {
            logger.error("文件上传异常:{}" , e.getMessage() , e);
            baseResponse = new BaseResponse(ReturnCode.NORMAL_ERROR , e.getMessage());
        }
        return baseResponse;
    }
}
